var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { User, Role } = require('../model/model');

// JWT密钥
const JWT_SECRET = 'rbac-system-secret-key';

// 验证Token中间件
const authMiddleware = (req, res, next) => {
  const token = req.header('x-auth-token');
  
  if (!token) {
    return res.status(401).json({ success: false, message: '无访问权限，请先登录' });
  }
  
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ success: false, message: '无效的Token' });
  }
};

// 权限检查中间件
const checkPermission = (permission) => {
  return (req, res, next) => {
    console.log('权限检查:', { userRole: req.user.role, permission, user: req.user });
    
    // 支持中英文角色名
    if (req.user.role === '老板' || req.user.role === 'owner' || 
        req.user.permissions?.includes('all') || req.user.permissions?.includes(permission)) {
      next();
    } else {
      res.status(403).json({ success: false, message: '权限不足' });
    }
  };
};

// 获取员工列表
router.get('/', authMiddleware, checkPermission('user:view'), async function(req, res) {
  try {
    const { page = 1, limit = 50, search = '' } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    let query = {};
    if (search) {
      query.$or = [
        { username: { $regex: search, $options: 'i' } },
        { phone: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 查询用户总数
    const total = await User.countDocuments(query);
    
    // 查询用户列表
    const users = await User.find(query)
      .populate('role')
      .populate('store')
      .select('-password')
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createTime: -1 });
    
    // 格式化返回数据
    const formattedUsers = users.map(user => ({
      _id: user._id,
      id: user._id,
      employeeId: user._id.toString().slice(-6).toUpperCase(),
      name: user.username,
      phone: user.phone || '',
      role: user.role ? user.role.name : '员工',
      status: user.status || 'active',
      storeId: user.store ? user.store._id : null,
      storeName: user.store ? user.store.name : '',
      joinDate: user.createTime ? user.createTime.toISOString().split('T')[0] : new Date().toISOString().split('T')[0]
    }));
    
    res.json({
      success: true,
      data: formattedUsers,
      total,
      page: parseInt(page),
      limit: parseInt(limit)
    });
  } catch (error) {
    console.error('获取员工列表失败:', error);
    res.status(500).json({ success: false, message: '获取员工列表失败', error: error.message });
  }
});

// 创建员工
router.post('/', authMiddleware, checkPermission('user:add'), async function(req, res) {
  try {
    const { name, phone, password, role, storeId } = req.body;
    
    console.log('创建员工请求:', { name, phone, password, role, storeId, body: req.body });
    
    // 验证必填字段
    if (!name || !password) {
      return res.status(400).json({ success: false, message: '姓名和密码为必填项' });
    }
    
    // 检查用户名是否已存在
    const existingUser = await User.findOne({ username: name });
    if (existingUser) {
      return res.status(400).json({ success: false, message: '员工姓名已存在' });
    }
    
    // 查找对应角色
    let roleDoc;
    if (role === 'manager') {
      roleDoc = await Role.findOne({ name: '管理员' });
    } else {
      roleDoc = await Role.findOne({ name: '员工' });
    }
    
    if (!roleDoc) {
      return res.status(400).json({ success: false, message: '指定的角色不存在' });
    }
    
    console.log('找到角色:', roleDoc);
    
    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    
    // 创建新用户
    const newUser = new User({
      username: name,
      password: hashedPassword,
      phone: phone || '',
      email: `${name}@company.com`, // 生成默认邮箱
      role: roleDoc._id,
      store: storeId || null,
      status: 'active'
    });
    
    console.log('准备保存用户:', newUser);
    
    await newUser.save();
    
    console.log('用户保存成功:', newUser._id);
    
    res.status(201).json({ 
      success: true, 
      message: '员工添加成功',
              data: {
          _id: newUser._id,
          id: newUser._id,
          employeeId: newUser._id.toString().slice(-6).toUpperCase(),
          name: newUser.username,
          phone: newUser.phone,
          role: roleDoc.name,
          storeId: newUser.store || null,
          status: 'active',
          joinDate: newUser.createTime.toISOString().split('T')[0]
        }
      });
  } catch (error) {
    console.error('创建员工失败:', error);
    res.status(500).json({ success: false, message: '创建员工失败', error: error.message });
  }
});

// 更新员工职位
router.put('/:id/role', authMiddleware, checkPermission('user:edit'), async function(req, res) {
  try {
    const { id } = req.params;
    const { newRole } = req.body;
    
    // 只有老板可以调整职位
    if (req.user.role !== '老板' && req.user.role !== 'owner') {
      return res.status(403).json({ success: false, message: '只有老板可以调整员工职位' });
    }
    
    // 查找对应角色
    let roleDoc;
    if (newRole === 'manager') {
      roleDoc = await Role.findOne({ name: '管理员' });
    } else {
      roleDoc = await Role.findOne({ name: '员工' });
    }
    
    if (!roleDoc) {
      return res.status(400).json({ success: false, message: '指定的角色不存在' });
    }
    
    // 更新用户角色
    const user = await User.findByIdAndUpdate(
      id,
      { role: roleDoc._id },
      { new: true }
    ).populate('role');
    
    if (!user) {
      return res.status(404).json({ success: false, message: '员工不存在' });
    }
    
    res.json({
      success: true,
      message: '职位调整成功',
      data: {
        employeeId: user._id.toString().slice(-6).toUpperCase(),
        name: user.username,
        role: user.role.name
      }
    });
  } catch (error) {
    console.error('更新员工职位失败:', error);
    res.status(500).json({ success: false, message: '更新员工职位失败', error: error.message });
  }
});

// 更新员工信息
router.put('/:id', authMiddleware, checkPermission('user:edit'), async function(req, res) {
  try {
    const { id } = req.params;
    const { name, phone, role, status, storeId } = req.body;
    
    // 验证必填字段
    if (!name) {
      return res.status(400).json({ success: false, message: '员工姓名为必填项' });
    }
    
    // 检查用户名是否已存在（排除当前用户）
    const existingUser = await User.findOne({ username: name, _id: { $ne: id } });
    if (existingUser) {
      return res.status(400).json({ success: false, message: '员工姓名已存在' });
    }
    
    // 查找对应角色
    let roleDoc;
    if (role === 'owner') {
      roleDoc = await Role.findOne({ name: '老板' });
    } else if (role === 'manager') {
      roleDoc = await Role.findOne({ name: '管理员' });
    } else {
      roleDoc = await Role.findOne({ name: '员工' });
    }
    
    if (!roleDoc) {
      return res.status(400).json({ success: false, message: '指定的角色不存在' });
    }
    
    // 构建更新数据
    const updateData = {
      username: name,
      phone: phone || '',
      role: roleDoc._id,
      status: status || 'active',
      store: storeId || null
    };
    
    // 更新用户信息
    const user = await User.findByIdAndUpdate(
      id,
      updateData,
      { new: true }
    ).populate('role');
    
    if (!user) {
      return res.status(404).json({ success: false, message: '员工不存在' });
    }
    
    res.json({
      success: true,
      message: '员工信息更新成功',
              data: {
          _id: user._id,
          id: user._id,
          employeeId: user._id.toString().slice(-6).toUpperCase(),
          name: user.username,
          phone: user.phone,
          role: user.role ? user.role.name : '员工',
          status: user.status,
          storeId: user.store || null,
          joinDate: user.createTime ? user.createTime.toISOString().split('T')[0] : new Date().toISOString().split('T')[0]
        }
      });
  } catch (error) {
    console.error('更新员工信息失败:', error);
    res.status(500).json({ success: false, message: '更新员工信息失败', error: error.message });
  }
});

// 更新员工状态
router.put('/:id/status', authMiddleware, checkPermission('user:edit'), async function(req, res) {
  try {
    const { id } = req.params;
    const { newStatus } = req.body;
    
    console.log('更新员工状态:', { id, newStatus, body: req.body });
    
    // 验证状态值
    if (!['active', 'inactive'].includes(newStatus)) {
      return res.status(400).json({ success: false, message: '无效的状态值' });
    }
    
    // 更新用户状态
    const user = await User.findByIdAndUpdate(
      id,
      { status: newStatus },
      { new: true }
    );
    
    if (!user) {
      return res.status(404).json({ success: false, message: '员工不存在' });
    }
    
    res.json({
      success: true,
      message: '状态更新成功',
      data: {
        employeeId: user._id.toString().slice(-6).toUpperCase(),
        name: user.username,
        status: newStatus
      }
    });
  } catch (error) {
    console.error('更新员工状态失败:', error);
    res.status(500).json({ success: false, message: '更新员工状态失败', error: error.message });
  }
});

// 获取员工统计信息
router.get('/stats', authMiddleware, checkPermission('user:view'), async function(req, res) {
  try {
    const totalEmployees = await User.countDocuments();
    const activeEmployees = await User.countDocuments({ status: 'active' });
    const managers = await User.countDocuments({ 'role.name': '管理员' });
    
    res.json({
      success: true,
      data: {
        total: totalEmployees,
        active: activeEmployees,
        managers: managers
      }
    });
  } catch (error) {
    console.error('获取员工统计失败:', error);
    res.status(500).json({ success: false, message: '获取员工统计失败', error: error.message });
  }
});

// 批量导入员工
router.post('/import', authMiddleware, checkPermission('user:add'), async function(req, res) {
  try {
    // 这里需要先安装multer和xlsx依赖
    // npm install multer xlsx
    
    const multer = require('multer');
    const xlsx = require('xlsx');
    
    // 配置multer
    const upload = multer({
      storage: multer.memoryStorage(),
      limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
      },
      fileFilter: (req, file, cb) => {
        // 只允许Excel文件
        if (file.mimetype === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
            file.mimetype === 'application/vnd.ms-excel') {
          cb(null, true);
        } else {
          cb(new Error('只允许上传Excel文件'), false);
        }
      }
    }).single('file');
    
    // 处理文件上传
    upload(req, res, async function(err) {
      if (err) {
        return res.status(400).json({ success: false, message: err.message });
      }
      
      if (!req.file) {
        return res.status(400).json({ success: false, message: '请选择要上传的文件' });
      }
      
      try {
        // 解析Excel文件
        const workbook = xlsx.read(req.file.buffer, { type: 'buffer' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const data = xlsx.utils.sheet_to_json(worksheet, { header: 1 });
        
        // 验证表头
        const headers = data[0];
        const expectedHeaders = ['姓名', '电话', '初始密码', '职位'];
        
        if (!headers || headers.length < 4) {
          return res.status(400).json({ 
            success: false, 
            message: '文件格式错误，请确保包含：姓名、电话、初始密码、职位列' 
          });
        }
        
        // 验证表头是否匹配
        for (let i = 0; i < expectedHeaders.length; i++) {
          if (headers[i] !== expectedHeaders[i]) {
            return res.status(400).json({ 
              success: false, 
              message: `表头格式错误，第${i+1}列应为"${expectedHeaders[i]}"，实际为"${headers[i]}"` 
            });
          }
        }
        
        // 处理数据行
        const employees = [];
        const errors = [];
        const successCount = 0;
        
        for (let i = 1; i < data.length; i++) {
          const row = data[i];
          if (!row || row.length === 0) continue; // 跳过空行
          
          const [name, phone, password, role] = row;
          
          // 验证必填字段
          if (!name || !password) {
            errors.push(`第${i+1}行：姓名和密码为必填项`);
            continue;
          }
          
          // 验证手机号格式
          if (phone && !/^1[3-9]\d{9}$/.test(String(phone))) {
            errors.push(`第${i+1}行：手机号格式不正确`);
            continue;
          }
          
          // 验证职位
          const validRoles = ['员工', '管理员'];
          if (role && !validRoles.includes(role)) {
            errors.push(`第${i+1}行：职位只能是"员工"或"管理员"`);
            continue;
          }
          
          employees.push({
            name: String(name).trim(),
            phone: phone ? String(phone).trim() : '',
            password: String(password).trim(),
            role: role ? String(role).trim() : '员工'
          });
        }
        
        if (errors.length > 0) {
          return res.status(400).json({ 
            success: false, 
            message: '数据验证失败', 
            errors 
          });
        }
        
        // 批量创建员工
        const createdEmployees = [];
        const failedEmployees = [];
        
        for (const employee of employees) {
          try {
            // 检查用户名是否已存在
            const existingUser = await User.findOne({ username: employee.name });
            if (existingUser) {
              failedEmployees.push({
                name: employee.name,
                error: '员工姓名已存在'
              });
              continue;
            }
            
            // 查找对应角色
            let roleDoc;
            if (employee.role === '管理员') {
              roleDoc = await Role.findOne({ name: '管理员' });
            } else {
              roleDoc = await Role.findOne({ name: '员工' });
            }
            
            if (!roleDoc) {
              failedEmployees.push({
                name: employee.name,
                error: '指定的角色不存在'
              });
              continue;
            }
            
            // 密码加密
            const salt = await bcrypt.genSalt(10);
            const hashedPassword = await bcrypt.hash(employee.password, salt);
            
            // 创建新用户
            const newUser = new User({
              username: employee.name,
              password: hashedPassword,
              phone: employee.phone,
              email: `${employee.name}@company.com`,
              role: roleDoc._id,
              status: 'active'
            });
            
            await newUser.save();
            
            createdEmployees.push({
              _id: newUser._id,
              id: newUser._id,
              employeeId: newUser._id.toString().slice(-6).toUpperCase(),
              name: newUser.username,
              phone: newUser.phone,
              role: roleDoc.name,
              status: 'active',
              joinDate: newUser.createTime.toISOString().split('T')[0]
            });
            
          } catch (error) {
            failedEmployees.push({
              name: employee.name,
              error: error.message
            });
          }
        }
        
        res.json({
          success: true,
          message: `批量导入完成，成功导入${createdEmployees.length}个员工，失败${failedEmployees.length}个`,
          data: {
            created: createdEmployees,
            failed: failedEmployees,
            total: employees.length,
            successCount: createdEmployees.length,
            failedCount: failedEmployees.length
          }
        });
        
      } catch (error) {
        console.error('解析Excel文件失败:', error);
        res.status(500).json({ success: false, message: '解析Excel文件失败', error: error.message });
      }
    });
    
  } catch (error) {
    console.error('批量导入员工失败:', error);
    res.status(500).json({ success: false, message: '批量导入员工失败', error: error.message });
  }
});

module.exports = router; 